import json
import time


from django.http import JsonResponse

from blueking.component.shortcuts import get_client_by_request
from home_application.constant import JOB_BK_BIZ_ID, SEARCH_FILE_PLAN_ID, MAX_ATTEMPTS, WAITING_CODE, \
    JOB_RESULT_ATTEMPTS_INTERVAL, SUCCESS_CODE, WEB_SUCCESS_CODE


def search_file(request):
    """
    根据主机IP、文件目录和文件后缀,查询符合条件的主机文件
    :param request:
    :return:
    """
    host_id_list_str = request.GET.get('host_id_list')
    host_id_list = [int(bk_host_id) for bk_host_id in host_id_list_str.split(',')]
    kwargs = {
        "bk_scope_type": "biz",
        "bk_scope_id": JOB_BK_BIZ_ID,
        "job_plan_id": SEARCH_FILE_PLAN_ID,
        "global_var_list": [
            {
                "name": "list",
                "server": {
                    "host_id_list": host_id_list,
                }
            },
            {
                "name" : "path",
                "value" : request.GET.get("search_path"),
            },
            {
                "name" : "suffix",
                "value" : request.GET.get("suffix"),
            }
        ]
    }
    client = get_client_by_request(request)
    result = client.jobv3.execute_job_plan(kwargs)
    job_instance_id = result.get("data").get("job_instance_id")
    kwargs = {
        "bk_scope_type": "biz",
        "bk_scope_id": JOB_BK_BIZ_ID,
        "job_instance_id": job_instance_id
    }
    attempts = 0
    while attempts < MAX_ATTEMPTS:
        result = client.jobv3.get_job_instance_status(kwargs)
        step_instance_list =result.get("data").get("step_instance_list")
        if step_instance_list[0].get("status") == WAITING_CODE:
            time.sleep(JOB_RESULT_ATTEMPTS_INTERVAL)
        elif step_instance_list[0].get("status") != SUCCESS_CODE:
            res_data = {
                "result": False,
                "code":0,
                "message": "search failed"
            }
            return JsonResponse(res_data)
        elif step_instance_list[0].get("status") == SUCCESS_CODE:
            break
        attempts += 1
    step_instance_id = step_instance_list[0].get("step_instance_id")
    log_list = []
    for bk_host_id in host_id_list:
        data = {
            "bk_scope_type" :"biz",
            "bk_scope_id" : JOB_BK_BIZ_ID,
            "job_instance_id" : job_instance_id,
            "step_instance_id" : step_instance_id,
            "bk_host_id" : bk_host_id
        }
        response = client.jobv3.get_job_instance_ip_log(**data)
        response = response.get("data")
        step_res = response.get("log_content")
        json_step_res = json.loads(step_res)
        json_step_res["bk_host_id"]=response.get("bk_host_id")
        log_list.append(json_step_res)
    res_data = {
        "result": True,
        "code":WEB_SUCCESS_CODE,
        "data": log_list
    }
    return JsonResponse(res_data)

